package com.sunnada.edu.system.pub.util;


import java.util.Properties;

import org.springframework.beans.factory.FactoryBean;

public class PropertiesEncryptFactoryBean implements FactoryBean {
	private Properties properties;

	public Object getObject() throws Exception {
		return getProperties();
	}

	@SuppressWarnings("unchecked")
	public Class getObjectType() {
		return Properties.class;
	}

	public boolean isSingleton() {
		return true;
	}

	public Properties getProperties() {
		return this.properties;
	}

	public void setProperties(Properties inProperties) {
		this.properties = inProperties;
		String originalUsername = this.properties.getProperty("username");
		String originalPassword = this.properties.getProperty("password");
		if (originalUsername != null) {
			String newUsername = deEncryptUsername(originalUsername);
			this.properties.put("username", newUsername);
		}
		if (originalPassword != null) {
			String newPassword = deEncryptPassword(originalPassword);
			this.properties.put("password", newPassword);
		}
	}

	private String deEncryptUsername(String originalUsername) {
		// return encryptString(originalUsername);
		return DES3.decrypt(originalUsername);
	}

	private String deEncryptPassword(String originalPassword) {
		// return encryptString(originalPassword);
		return DES3.decrypt(originalPassword);
	}

	@SuppressWarnings("unused")
	private String deEncryptString(String originalString) {
		StringBuilder newString = new StringBuilder();
		for (int i = 0; i < originalString.length(); ++i) {
			char eachChar = originalString.charAt(i);
			char newChar = (char) (eachChar + i);
			newString.append(newChar);
		}
		return newString.toString();
	}

	private String encryptString(String str) {
		String result = "";
		try {
			byte[] strByte = str.getBytes();
			for (int i = 0; i < str.length(); ++i)
				if (strByte[i] <= 40)
					result = result + (char) (strByte[i] + 10);
				else if ((strByte[i] > 40) && (strByte[i] <= 80))
					result = result + (char) (strByte[i] + 50);
				else if ((strByte[i] > 80) && (strByte[i] <= 120))
					result = result + (char) (strByte[i] - 30);
				else if (strByte[i] > 120)
					result = result + (char) (strByte[i] + 6);
		} catch (Exception e) {
			System.err.println("加密出错,出错原因=" + e.toString());
			result = "-1";
		}
		return result;
	}
}